package com.ln.common;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.ln.pojo.impl.UserPOJO;

public class WebAuthorityAccessInterceptor extends HandlerInterceptorAdapter {

	private static final String DIRECTPASS = "regsub,login,logsub,logout,index,show,space,error,test";

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) {

		String URI = request.getRequestURI();

		Date time = new Date();

		System.out.printf("===> %d : %d : %d\n", time.getHours(),
				time.getMinutes(), time.getSeconds());
		System.out.println("URI: " + URI);

		if (URI.indexOf("/", 1) > -1) {
			URI = URI.substring(1, URI.indexOf("/", 1));
		} else {
			URI = URI.substring(1);
		}

		if (DIRECTPASS.contains(URI)) {
			return true;
		}

		UserPOJO LOGIN_USER = (UserPOJO) WebUtils.getSessionAttribute(request,
				"LOGIN_USER");
		if (LOGIN_USER == null) {
			try {
				response.sendRedirect("/login");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}
		return true;
	}

}
